package com.wyh.filter;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

/**
 * @author wuyuhan
 * @date 2021/1/26 21:40
 */
@Activate(group = {CommonConstants.CONSUMER})
public class TimeFilter implements Filter {

    public static HashMap<String, TreeSet<ReqTime>> REQ_TIME = new HashMap<String, TreeSet<ReqTime>>();

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long endTime = System.currentTimeMillis();

//        System.out.println("耗时："+(endTime-startTime));

        String service = invocation.getServiceName();
        String methodName = invocation.getMethodName();
        String key=service+":"+methodName;
        synchronized (REQ_TIME) {
            TreeSet<ReqTime> treeSet = REQ_TIME.get(key);
            if(treeSet == null) {
                treeSet = new TreeSet<ReqTime>();
                REQ_TIME.put(key, treeSet);
            }
            treeSet.add(new ReqTime(startTime,endTime - startTime));
        }
        return result;
    }

    public class ReqTime implements Comparable<ReqTime> {
        public long sendTime;  //请求时间， 毫秒
        public long spendTime; //请求耗时， 毫秒

        public ReqTime(long sendTime, long spendTime) {
            this.sendTime = sendTime;
            this.spendTime = spendTime;
        }

        @Override
        public int compareTo(ReqTime o) {
            if (spendTime == o.spendTime) {
                return 0;
            } else if (spendTime < o.spendTime) {
                return -1;
            } else {
                return 1;
            }
        }
    }
}
